package serverlogic;

import java.sql.ResultSet;
import java.sql.SQLException;

import net.com.sunkey.messagehandler.JoinServerSucceedResponseHandler;
import net.com.sunkey.messagehandler.ServerErrorResponseHandler;
import net.com.sunkey.messagehandler.UserNotFoundResponseHandler;
import net.com.sunkey.protobuf.JoinServerRequest.JoinServerRequestData;
import net.com.sunkey.protobuf.Protocol;
import net.com.sunkey.serverlogic.Module;
import net.com.sunkey.serverlogic.Server;
import net.com.sunkey.serverlogic.User;

public class ModuleJoinServer extends Module {

	@Override
	public int invoke(Object data, Object channel) throws Exception {
		System.out.println("["+channel.hashCode()+"]["+Protocol.MessageHandler.JoinServerRequest_VALUE+"]JoinServerRequest");
		JoinServerRequestData requestData=(JoinServerRequestData)data;
//		if (!User.checkCertificate(requestData.getCertificate())){
//			ServerErrorResponseHandler.invoke(Protocol.ReturnStatus.STATUS_EXPIRED_CERTIFICATE_VALUE,channel);
//		}
		
		if (!requestData.getUsername().matches("[a-zA-Z0-9\u4e00-\u9fa5@.-]{2,20}")){
			return ServerErrorResponseHandler.invoke(Protocol.ReturnStatus.STATUS_AUTH_FAILED_VALUE,channel);		
		}
		if (!requestData.getPassword().matches("[a-zA-Z0-9@.-]{1,20}")){
			return ServerErrorResponseHandler.invoke(Protocol.ReturnStatus.STATUS_AUTH_FAILED_VALUE,channel);
		}			
		
		int accountID=login(requestData.getUsername(),requestData.getPassword());
		if (accountID<0){
			return ServerErrorResponseHandler.invoke(Protocol.ReturnStatus.STATUS_AUTH_FAILED_VALUE,channel);
		}
		User user=getUser(accountID,channel);
		if (user==null){
			UserNotFoundResponseHandler.invoke(accountID,channel);
		}else{
			JoinServerSucceedResponseHandler.invoke(user,channel);
		}
		loginLog(requestData.getUsername(),requestData.getVersion(),requestData.getAgent(),
				requestData.getOs(),requestData.getPixel(),requestData.getCharset(),requestData.getClientSpeed(),channel);		
		return Protocol.MessageHandler.JoinServerRequest_VALUE;
	}

	private void loginLog(String username, String version, String agent,
			String os, String pixel, String charset, int clientSpeed,
			Object channel) throws SQLException {
		StringBuffer sql = new StringBuffer();
		sql.append(
				"INSERT INTO login (logintime,username,version,agent,os,pixel,charset,clientspeed,ip)VALUES (NOW(),'")
				.append(username).append("','").append(version).append("','")
				.append(agent).append("','").append(os).append("','")
				.append(pixel).append("','").append(charset).append("','")
				.append(clientSpeed).append("','")
				.append(Server.getIP(channel)).append("')");

		Server.getConnection().createStatement().execute(sql.toString());

	}

	private User getUser(int accountID, Object channel) throws SQLException {

		StringBuffer sql = new StringBuffer();
		sql = new StringBuffer();
		sql.append(
				"SELECT user.*,account.money FROM user,account WHERE user.accountID=account.id AND accountID='")
				.append(accountID).append("'");
		ResultSet rs = Server.getConnection().createStatement().executeQuery(sql.toString());
		if (rs.next()) {
			User user = new User(rs.getInt("id"), rs.getString("name"), channel);
			user.addProperty("sex", rs.getString("sex"));
			user.addProperty("job", rs.getString("job"));
			user.addProperty("level", rs.getString("level"));
			user.addProperty("hair", rs.getString("hair"));
			user.addProperty("face", rs.getString("face"));
			user.addProperty("cloth", rs.getString("cloth"));
			user.addProperty("background", rs.getString("background"));
			user.addProperty("suite", rs.getString("suite"));

			user.addExtProperty("accountID", rs.getString("accountID"));
			user.addExtProperty("exp", rs.getString("exp"));
			user.addExtProperty("sp", rs.getString("sp"));
			user.addExtProperty("hp", rs.getString("hp"));
			user.addExtProperty("gold", rs.getString("gold"));
			user.addExtProperty("strength", rs.getString("strength"));
			user.addExtProperty("intellect", rs.getString("intellect"));
			user.addExtProperty("dexterity", rs.getString("dexterity"));
			user.addExtProperty("luck", rs.getString("luck"));
			user.addExtProperty("helmet", rs.getString("helmet"));
			user.addExtProperty("armor", rs.getString("armor"));
			user.addExtProperty("weapon", rs.getString("weapon"));
			user.addExtProperty("necklace", rs.getString("necklace"));
			user.addExtProperty("ring", rs.getString("ring"));
			user.addExtProperty("money", rs.getString("money"));

			user.initUser();
			return user;
		}

		return null;
	}

	private int login(String username, String password) throws SQLException {

		StringBuffer sql = new StringBuffer();
		sql.append("SELECT id FROM account WHERE active=1 AND username='")
				.append(username).append("' AND password='").append(password)
				.append("'");
		ResultSet rs = Server.getConnection().createStatement().executeQuery(sql.toString());
		if (rs.next()) {
			return rs.getInt(1);
		}

		return -1;
	}
	@Override
	public int register() {
		return Protocol.MessageHandler.JoinServerRequest_VALUE;
	}

}
